<script setup lang="ts">
import {reactive, ref} from 'vue';
import {message, type SelectProps} from 'ant-design-vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import {postKnowledgeBaseCreateGroup, postNoteCreateNote} from "@/apis/student";

//创建笔记模态框设置
const modalNote = ref<boolean>(false);
const loading = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
//form表单
const noteFormRef = ref<any>(null)
const note = reactive<{name:string,picture:any,info?:string}>({
  name: '',
  picture: '',
  info:''
})
//创建笔记模态框方法
//显示模态框
const showModalNote = () => {
  modalNote.value = true;
};
//关闭模态框
const handleCancelNote = () => {
  note.name=''
  modalNote.value = false
  loadingImg.value = false
};
//图片上传
const fileList = ref([]);
const loadingImg = ref<boolean>(false);
const imageUrl = ref<string>('');
function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}
const handlePicturnUp = (param: UploadChangeParam) => {
  const {file} = param
  console.log(file)
  message.success("文件已获取")
}
const handlePicturnUpErr = () => {
  message.error("文件不符合类型")
}
const handlePicturnChange = (info:UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loadingImg.value = true;
    return;
  }
  if (info.file.status === 'done') {
    console.log(info.file.originFileObj)
    // Get this url from response in real world.
    getBase64(info.file.originFileObj as Blob, (base64Url: string) => {
      imageUrl.value = base64Url;
      loadingImg.value = false;
    });
  }
  if (info.file.status === 'error') {
    loadingImg.value = false;
    message.error('upload error');
  }
}
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('这不是一个图片文件');
  }
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isLt2M) {
    message.error('图片大小不得超过 5MB!');
  }
  return isJpgOrPng && isLt2M;
};


//异步请求方法
const handleOkNote = () => {
  if (!note.name){
    message.warning('请设置笔记名称')
    return
  }
  // 创建笔记请求
  postNoteCreateNote({
    noteName: note.name,
    noteCoverImg: note.picture
  })
  confirmLoading.value = true;
  loading.value = true;
  //请求处理
  setTimeout(() => {
    loading.value = false;
    modalNote.value = false;
    confirmLoading.value = false;
    message.success(`创建${note.name}成功`)
  }, 2000);
};

//创建收藏夹模态框处理
const modalFavorites = ref<boolean>(false)
//input值绑定
const favorites = reactive<{name:string,info:string,label?:string}>({
  name:'',
  info: '',
  label:''
})
const showModalFavorites = () => {
  modalFavorites.value = true
}
const handleCancelFavorites = () => {
  favorites.name =''
  favorites.info=''
  modalFavorites.value = false
}
const handleOkFavorites = () => {
  if(favorites.name){
    //请求发送
    message.info(`创建分组 [ ${favorites.name} ] 成功`)
    // 创建收藏夹
    postKnowledgeBaseCreateGroup({
      knowledgebaseName: favorites.name,
      knowledgebaseIntro: favorites.info,
      type:favorites.label
    }).then((res) => {
      console.log(res)
    }).catch((err) =>{
      console.log(err)
    })
    modalFavorites.value = false
  } else {
    message.warn("请填写文件夹名称")
  }
  favorites.name =''
  favorites.info=''
}
const handleSelectChange = (param:any) => {
  console.log(param)
}
const labelOptions = ref<SelectProps['options']>([
  {
    value: '无',
    label: '无',
  },
  {
    value: 'Java',
    label: 'Java',
  },
  {
    value: 'python',
    label: 'python',
  },
  {
    value: 'C',
    label: 'C',
  },
  {
    value: 'C#',
    label: 'C#',
  },
  {
    value: 'C++',
    label: 'C++',
  },
  {
    value: 'Vue',
    label: 'Vue',
  },
  {
    value: 'Spring',
    label: 'Spring',
  },
  {
    value: 'Flask',
    label: 'Flask',
  },
  {
    value: 'Mybatis',
    label: 'Mybatis',
  },
  {
    value: 'MySql',
    label: 'MySql',
  },
  {
    value: 'Redis',
    label: 'Redis',
  },
  {
    value: 'AIGC',
    label: 'AIGC',
  },
  {
    value: '大数据',
    label: '大数据',
  },
  {
    value: '云平台',
    label: '云平台',
  },
  {
    value: '运维',
    label: '运维',
  },
  {
    value: '硬件开发',
    label: '硬件开发',
  },
  {
    value: '服务器',
    label: '服务器',
  },
])
//form表单方法设置
</script>

<template>
  <a-space size="large">
    <a-button class="button" type="primary" @click="showModalNote">
      <span class="span-title">创建笔记</span><br>
      <span class="span-info">文档、笔记、代码学习</span>
    </a-button>
    <a-modal v-model:open="modalNote" title="笔记信息" :confirm-loading="confirmLoading" @cancel="handleCancelNote">
      <template #footer>
        <a-button key="back" @click="handleCancelNote">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOkNote">创建</a-button>
      </template>
      <a-divider></a-divider>
      <a-form
        ref="noteFormRef"
        :model="note"
      >
        <a-form-item label="笔记名称">
          <a-input v-model:value="note.name"></a-input>
        </a-form-item>
        <a-form-item label="笔记简介">
          <a-textarea v-model:value="note.info"
                      placeholder="简述笔记内容"
                      :maxlength="200"
                      show-count
                      allow-clear
          ></a-textarea>
        </a-form-item>
        <a-form-item label="笔记封面">
          <a-upload
              v-model:file-list="fileList"
              accept="image/*"
              :max-count="1"
              name="noteAvatar"
              list-type="picture-card"
              class="avatar-uploader"
              action="#"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              :custom-request="handlePicturnUp"
              @drop="handlePicturnUp"
              @reject="handlePicturnUpErr"
              @change="handlePicturnChange"

          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="loadingImg"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
      <a-divider></a-divider>
    </a-modal>

    <a-button class="button" type="primary" @click="showModalFavorites">
      <span class="span-title">创建笔记分组</span><br>
      <span class="span-info">更好的整理笔记，学习模型系统</span>
    </a-button>

    <a-modal v-model:open="modalFavorites" title="收藏夹信息">
      <template #footer>
        <a-button key="back" @click="handleCancelFavorites">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOkFavorites">创建</a-button>
      </template>
      <a-divider></a-divider>
      <a-form
          ref="favoritesForm"
          :model="favorites"
      >
        <a-form-item label="收藏夹名称">
          <a-input v-model:value="favorites.name" :maxlength="12"></a-input>
        </a-form-item>
        <a-form-item label="收藏夹标签">
          <a-select v-model:value="favorites.label" @change="handleSelectChange" :options="labelOptions"></a-select>
        </a-form-item>
        <a-form-item label="收藏夹简述">
          <a-textarea v-model:value="favorites.info"
                      placeholder="简述收藏夹作用"
                      :maxlength="200"
                      show-count
                      allow-clear
          ></a-textarea>
        </a-form-item>
      </a-form>
      <a-divider></a-divider>
    </a-modal>
  </a-space>
</template>

<style scoped lang="scss">
.button{
  width: 15rem;
  height: 3.6rem;
  overflow: hidden;
}
.span-title{
  font-weight: bold;
  font-size: 1rem;
}
.span-info{
  font-size: .8rem;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
